package com.ruoyi.web.controller.app;

import java.io.*;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.framework.web.domain.server.Sys;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.IScbChannelService;
import com.ruoyi.system.service.IScbOrdersrecordService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.service.IScbNotesService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 市场部预约提醒Controller
 * 
 * @author ruoyi
 * @date 2024-06-19
 */
@Api("市场部预约提醒")
@RestController
@RequestMapping("/system/notes")
public class ScbNotesController extends BaseController
{
    @Autowired
    private IScbNotesService scbNotesService;
    @Autowired
    private IScbChannelService scbChannelService;
    @Autowired
    private IScbOrdersrecordService scbOrdersrecordService;
    /**
     * 查询市场部预约提醒列表
     */
    @ApiOperation("获取预约提醒列表")
    @PostMapping("/listyewu")
    public    HashMap<Object, Object>  listyewu(@RequestBody ScbNotes scbNotes)
    {
        HashMap<Object, Object> map = new HashMap<>();
        List<ScbNotes> list;
        if(scbNotes.getType()!=null&&scbNotes.getType().equals("1")){
           list = scbNotesService.selectdinScbNotesList(scbNotes);
        }else{
           list = scbNotesService.selectScbNotesList(scbNotes);
        }
        map.put("data",list);
        return map;

    }


    /**
     * 查询【请填写功能名称】列表
     */

    @PostMapping("/listChannel")
    public HashMap<Object, Object> listChannel(@RequestBody ScbChannel scbChannel)
    {
        HashMap<Object, Object> map = new HashMap<>();
        List<ScbChannel> list;
        if(scbChannel.getType()!=null&&scbChannel.getType().equals("1")){
             list = scbChannelService.selectdinScbChannelList(scbChannel);
        }else{
             list = scbChannelService.selectScbChannelList(scbChannel);
        }
        map.put("data",list);
        return map;
    }
    /**
     * 新增【请填写功能名称】
     */


    @PostMapping("/saveScbOrdersrecord")
    public AjaxResult saveScbOrdersrecord(@RequestBody ScbOrdersrecord scbOrdersrecord)
    {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String now = LocalDateTime.now().format(formatter);
        scbOrdersrecord.setId(now);
        scbOrdersrecord.setOnstates("待处理");
        return toAjax(scbOrdersrecordService.insertScbOrdersrecord(scbOrdersrecord));
    }
    @PostMapping("/cancelScbOrdersrecord")
    public AjaxResult cancelScbOrdersrecord(@RequestBody ScbOrdersrecord scbOrdersrecord)
    {
        scbOrdersrecord.setId(scbOrdersrecord.getId());
        scbOrdersrecord.setOnstates("已取消");
        return toAjax(scbOrdersrecordService.updateScbOrdersrecord(scbOrdersrecord));
    }
    @PostMapping("/listrecord")
    public    HashMap<Object, Object>  listrecord(@RequestBody ScbOrdersrecord scbOrdersrecord)
    {
        HashMap<Object, Object> map = new HashMap<>();
        List<ScbOrdersrecord> list;
            list = scbOrdersrecordService.selectScbOrdersrecordList(scbOrdersrecord);
        map.put("data",list);
        return map;

    }
    @PostMapping("/listrecordcount")
    public    HashMap<Object, Object>  listrecordcount(@RequestBody ScbOrdersrecord scbOrdersrecord)
    {
        HashMap<Object, Object> map = new HashMap<>();
        List<ScbOrdersrecord> list;
        list = scbOrdersrecordService.selectScbOrdersrecordListcount(scbOrdersrecord);
        map.put("count",list.size());
        return map;

    }
    @PostMapping("/importData")
    public void importData(@RequestParam("file") MultipartFile file, HttpServletResponse response) throws Exception
    {
        ExcelUtil<recordE> util = new ExcelUtil<recordE>(recordE.class);

        List<recordE> userList = util.importExcel(file.getInputStream());
        if(userList.size()<50000){
        List<recordE> longWords = userList.stream()
                .filter(e -> e.getName8().equals("组网协商速率不达标")).filter(e -> e.getName().contains("202405"))
                .collect(Collectors.toList());

        List<recordE> longWord2 = userList.stream()
                .filter(e -> !e.getName8().equals("组网协商速率不达标")).filter(e -> e.getName().contains("202405")) // Lambda表达式用于过滤长度大于4的单词
                .collect(Collectors.toList());

            //创建指定目录文件
            File f = new File(System.getProperty("user.dir")+"\\data\\text.xlsx");
            if(!f.exists())
            {
                f.createNewFile();
            }
            BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(f));




        try {
            this.setExcelResponseProp(response, "质差用户关怀");
            // 模拟根据条件在数据库查询数据
            //这个实现方式非常简单直接，使用EasyExcel的write方法将查询到的数据进行处理，以流的形式写出即可
            ExcelWriter excelWriter = EasyExcel.write(outputStream).head(recordE.class)
                    .build();

         /*   EasyExcel.write(outputStream,recordE.class)//对应的导出实体类
                    .excelType(ExcelTypeEnum.XLSX).sheet("问题反馈表")//excel文件类型，包括CSV、XLS、XLSX
                   //导出sheet页名称
                    .doWrite(longWords);*/
            ExcelWriterSheetBuilder userExcelSheet = new ExcelWriterSheetBuilder();
            userExcelSheet.sheetName("组网协商速率不达标");
            userExcelSheet.sheetNo(0);
            excelWriter.write(longWords, userExcelSheet.build());

            ExcelWriterSheetBuilder classExcelSheet = new ExcelWriterSheetBuilder();
            classExcelSheet.sheetName("其他");
            classExcelSheet.sheetNo(1);
            excelWriter.write(longWord2, classExcelSheet.build());
            excelWriter.finish();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            outputStream.flush();
            outputStream.close();
        }
        }else{
            System.out.println("表格数据过多");
        }

    }
    @PostMapping("/export")
    public void export(HttpServletResponse response) throws IOException {
        String filePath = System.getProperty("user.dir")+"\\data\\text.xlsx";
        File file = new File(filePath);
        FileInputStream fis = new FileInputStream(file);
        OutputStream out = response.getOutputStream();
        this.setExcelResponseProp(response, "质差用户关怀");
        byte[] buffer = new byte[1024];
        int len;
        while ((len = fis.read(buffer)) != -1) {
            out.write(buffer, 0, len);
        }
        out.flush();
        out.close();
        fis.close();

    }
    private void setExcelResponseProp(HttpServletResponse response, String rawFileName) throws UnsupportedEncodingException {
        //设置内容类型
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        //设置编码格式
        response.setCharacterEncoding("utf-8");
        //设置导出文件名称（避免乱码）
        String fileName = URLEncoder.encode(rawFileName.concat(".xlsx"), "UTF-8");
        // 设置响应头
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName);
    }

}
